package com.adams.dcxt.action;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import net.sf.json.JSONObject;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.adams.dcxt.bean.Dishes;
import com.adams.dcxt.bean.Order;
import com.adams.dcxt.bean.OrderDishes;
import com.adams.dcxt.bean.Waiter;
import com.adams.dcxt.core.Contants;
import com.adams.dcxt.core.DateUtils;
import com.adams.dcxt.core.DishesTemp;
import com.adams.dcxt.core.Page;
import com.adams.dcxt.core.TableMaps;
import com.adams.dcxt.facade.OrderFacade;
import com.adams.dcxt.service.DishesService;
import com.adams.dcxt.service.OrderDishesService;
import com.adams.dcxt.service.OrderService;
import com.adams.dcxt.service.WaiterService;

/**
 * 我的菜单
 * 
 * @author 904912
 * 
 */
public class OrderAction extends BaseAction {

    private static final long serialVersionUID = -6833993806220247910L;
    private String tableId; // 餐桌号
    private static Logger logger = LoggerFactory.getLogger(OrderAction.class);
    private OrderFacade orderFacade;
    private String dids; // 菜单ID,用逗号分隔
    private String uid; // 服务员工号
    private DishesService dishesService;
    private String dname;// 菜单名
    private String price;// 价格
    private String count;// 份数
    private String did;// 菜单主键
    private String pwd; //服务员密码
    private OrderService orderService;
    private OrderDishesService orderDishesService;
    private  WaiterService waiterService;
    
    
    //开台
    
    public  String initTable(){
    	//服务员工号，密码 与桌号  ，1 检测用户名和密码是否正确
    	// 2 检测餐桌是否结账，未结账，直接提示加菜，已结初始化
    	Map response = new HashMap();
    	String msg="";
    	try{
    	Waiter  waiter= 	waiterService.validationWaiter(Long.parseLong(uid), pwd);
    	if(waiter==null){
    	//返回提示
    		msg="输入错误，用户不存在或与密码不匹配";
    		response.put("data", msg);
            response.put("success", false);
            write(JSONObject.fromObject(response).toString());
    		return null;
    	}else{
    	//开台
    		Order order = 	orderService.queryOrderByTableStatus(tableId);
    		if(order==null){
    	  //第一次
    			order  = new Order();
    			order.setOrderTime(DateUtils.getNowTime("yyyy-MM-dd HH:mm:ss"));
    			order.setTable(tableId);
    			order.setTotalMoney(0);
    			order.setStatus(Contants.ORDER_NO_CHECK);
    			order.setWaiterId(Long.parseLong(uid));
    			orderService.saveOrder(order);
    			response.put("data", waiter);
                response.put("success", true);
                
    		}else{
    			if(Contants.ORDER_NO_CHECK.equals(order.getStatus())){
    				//未结账，提示继续加菜
    				//update order
    				order.setWaiterId(Long.parseLong(uid));
    				order.setOrderTime(DateUtils.getNowTime("yyyy-MM-dd HH:mm:ss"));
    				orderService.update(order);
    				response.put("data", waiter);
    				response.put("next", "0"); //是否加菜
    				response.put("success", true);
    			}else if(Contants.ORDER_CHECK_OUT.equals(order.getStatus())){
    				//已经结账，新增一条记录
    				order.setWaiterId(Long.parseLong(uid));
    				order.setOrderTime(DateUtils.getNowTime("yyyy-MM-dd HH:mm:ss"));
    				order.setStatus("0");
    				order.setTable(tableId);
    				orderService.saveOrder(order);
    				response.put("data", waiter);
    				response.put("success", true);
    			}	  
    	  
    	  
    	  
      }
    	
    		
    }
    	
    
	}catch (Exception e) {
		response.put("data", "系统异常");
        response.put("success", false);
	}
	write(JSONObject.fromObject(response).toString());
    	return null;
    }
    
    
    public String removeATmpOrder() {
        // 根据菜单主键找出菜单 份数减一 份数为1 删除
        Set<DishesTemp> set = TableMaps.getInstance().getTempsByTableId(tableId);
        Map response = new HashMap();
        if (StringUtils.isBlank(did) || StringUtils.isBlank(tableId)) {
            response.put("data", "删除失败");
            response.put("success", false);
            write(JSONObject.fromObject(response).toString());
            return null;
        }
        if (set != null) {
            for (DishesTemp temp : set) {
                if (temp.getDishesId().toString().equals(did)) {
                    synchronized (temp) {
                        if ("1".equals(temp.getCount())) {
                            // 移除此对象
                            set.remove(temp);
                        } else {
                            // 减一
                            String count = temp.getCount();
                            int newcount = Integer.parseInt(count) - 1;
                            temp.setCount(String.valueOf(newcount));
                        }
                    }
                }
            }
        }
        response.put("data", "删除成功");
        response.put("success", true);
        write(JSONObject.fromObject(response).toString());
        return null;
    }

    /**
     * 存储临时选择菜单
     * 
     * @return
     */
    public String saveTmpOrder() {
        DishesTemp temp = new DishesTemp();
        temp.setName(dname);
        Map response = new HashMap();
        if (StringUtils.isBlank(did) || StringUtils.isBlank(tableId)) {
            response.put("data", "选择菜单失败");
            response.put("success", false);
            write(JSONObject.fromObject(response).toString());
            return null;
        } else {
            temp.setDishesId(Long.parseLong(did));
        }
        temp.setPrice(price);
        temp.setCount(count);
        TableMaps.getInstance().setTemp(tableId, temp);
        response.put("data", "选择菜单成功");
        response.put("success", true);
        write(JSONObject.fromObject(response).toString());
        return null;
    }

    public String getTmpOrder() {
        Set<DishesTemp> set = TableMaps.getInstance().getTempsByTableId(tableId);
        Map response = new HashMap();
        response.put("data", set);
        response.put("success", true);
        write(JSONObject.fromObject(response).toString());
        return null;
    }

    public String order() {
        Map response = new HashMap();
        try {
            if (StringUtils.isNotBlank(dids) && StringUtils.isNotBlank(uid) && StringUtils.isNotBlank(tableId)) {
                int totalMoney = 0;
                String dishesIds[] = dids.split(",");
                List<OrderDishes> oDishesList = new ArrayList<OrderDishes>();
                StringBuilder str = new StringBuilder();

                // 查询此桌是否已经有订单且未结账
                Order queryOrder = orderService.queryOrderByTable(tableId);
                //份数也是以逗号分开
                String countsList[] = count.split(",");    
                int i=0;
                for (String idStr : dishesIds) {
                    Dishes d = dishesService.get(Long.parseLong(idStr));
                            
                    if (d != null) {
                    	//更新点击数      
                        dishesService.updateTop(1, d.getDishesId());
                        
                        int price = d.getDishesPrice();
                        float rate = Float.parseFloat(d.getSpecialRate());
                        double finalPriceDouble = price * rate;
                        BigDecimal bd = new BigDecimal(finalPriceDouble);
                        int finalPrice = bd.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();
                        totalMoney += finalPrice;
                        OrderDishes od = new OrderDishes();
                        // 查询此订单号，是否有相同的菜
                        int ocount=0;
                        if(queryOrder==null){
                        	ocount = 0;
                        }else{
                        	ocount=   orderDishesService.queryCountDishesByTable(queryOrder.getId().toString(), idStr);
                        }
                        if(ocount>0){
                            //存在此菜单，更新份数
                            orderDishesService.updateOrderDishes(queryOrder.getId().toString(), idStr,Integer.parseInt(countsList[i]));
                        }else{
                            od.setDishes(d);
                            od.setCount(Integer.parseInt(countsList[i]));
                            oDishesList.add(od); 
                        }
                        str.append(d.getDishesId()).append(",");
                    }
                    i++;
                }
                String ids = "";
                if (str.length() > 0)
                    ids = str.substring(0, str.length() - 1);
                Order order = new Order();
                order.setOrderTime(DateUtils.getNowTime("yyyy-MM-dd HH:mm:ss"));
                order.setTable(tableId);
                order.setTotalMoney(totalMoney);
                order.setStatus(Contants.ORDER_NO_CHECK);
                order.setWaiterId(Long.parseLong(uid));
                orderFacade.placeOrder(order, oDishesList, queryOrder);
                TableMaps.getInstance().clearItem(tableId, ids);
                response.put("data", "下单成功");
                response.put("success", true);
            } else {
                response.put("data", "下单失败");
                response.put("success", false);

            }
        } catch (Exception e) {
            response.put("data", "下单失败");
            response.put("success", false);
            logger.error("下单失败原因：", e);
        }
        write(JSONObject.fromObject(response).toString());
        return null;

    }

    public String getOrderByTable() {
        Map response = new HashMap();
        Page<OrderDishes> page = new Page<OrderDishes>();
        setPage(page);
        try {
            page = orderFacade.getOrderDishes(tableId, page);
        } catch (Exception e) {
            logger.error("查询我的菜单错误:", e);
            response.put("data", "");
            response.put("success", false);
            write(JSONObject.fromObject(response).toString());
            return null;
        }
        Integer totalPage = page.getTotalPage();
        List<OrderDishes> list = page.getResultList();
        response.put("data", list);
        response.put("success", true);
        response.put("totalPage", totalPage);
        write(JSONObject.fromObject(response).toString());
        return null;
    }

    public String getTableId() {
        return tableId;
    }

    public void setTableId(String tableId) {
        this.tableId = tableId;
    }

    public OrderFacade getOrderFacade() {
        return orderFacade;
    }

    public void setOrderFacade(OrderFacade orderFacade) {
        this.orderFacade = orderFacade;
    }

    public String getDids() {
        return dids;
    }

    public void setDids(String dids) {
        this.dids = dids;
    }

    public String getUid() {
        return uid;
    }

    public void setUid(String uid) {
        this.uid = uid;
    }

    public DishesService getDishesService() {
        return dishesService;
    }

    public void setDishesService(DishesService dishesService) {
        this.dishesService = dishesService;
    }

    public String getDname() {
        return dname;
    }

    public void setDname(String dname) {
        this.dname = dname;
    }

    public String getPrice() {
        return price;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getCount() {
        return count;
    }

    public void setCount(String count) {
        this.count = count;
    }

    public String getDid() {
        return did;
    }

    public void setDid(String did) {
        this.did = did;
    }

    public OrderService getOrderService() {
        return orderService;
    }

    public void setOrderService(OrderService orderService) {
        this.orderService = orderService;
    }

    public OrderDishesService getOrderDishesService() {
        return orderDishesService;
    }

    public void setOrderDishesService(OrderDishesService orderDishesService) {
        this.orderDishesService = orderDishesService;
    }


	public WaiterService getWaiterService() {
		return waiterService;
	}


	public String getPwd() {
		return pwd;
	}


	public void setPwd(String pwd) {
		this.pwd = pwd;
	}


	public void setWaiterService(WaiterService waiterService) {
		this.waiterService = waiterService;
	}

}
